package Example1;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


@WebServlet("/Exam5")
public class Exam5 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf8");
        req.setCharacterEncoding("utf8");
        List<Student> list = null;
        try {
            list = getMess();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

//        ObjectMapper objectMapper = new ObjectMapper();
//        resp.getWriter().write(objectMapper.writeValueAsString(list));
    }

    public static List<Student> getMess() throws SQLException {
        DataSource dataSource = DBUtil.getDataSource();
        List<Student> list = new ArrayList<Student>();
        Connection connection = dataSource.getConnection();

        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);
        ResultSet resultSet = statement.executeQuery();
        while(resultSet.next()){
            Student student = new Student();
            student.setId(Integer.parseInt(resultSet.getString("id")));
            student.setName(resultSet.getString("name"));
            list.add(student);
        }
        statement.close();
        connection.close();
        return list;
    }
}
